import {createSlice} from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';

interface CounterState {
  count: number;
  isEdit: boolean;
}

const initialState = {count: 0} as CounterState;

export const counterSlice = createSlice({
  name: 'counter', // 命名空间，在调用action的时候会默认的设置为action的前缀
  // 初始值
  initialState,
  // 这里的属性会自动的导出为actions，在组件中可以直接通过dispatch进行触发
  reducers: {
    increment(state, {payload}) {
      // console.log(action);
      state.count = state.count + payload.step; // 内置了immutable
    },
    edit(state, {payload}) {
      state.isEdit = payload.value;
    },
    incrementByAmount(state, action: PayloadAction<number>) {
      state.count += action.payload;
    },
    decrement(state) {
      state.count -= 1;
    },
  },
});

// 导出actions
export const {increment, decrement, incrementByAmount, edit} =
  counterSlice.actions;

// 内置了thunk插件，可以直接处理异步请求
export const asyncIncrement: any = (payload: any) => (dispatch: any) => {
  setTimeout(() => {
    dispatch(increment(payload));
  }, 2000);
};

export default counterSlice.reducer; // 导出reducer，在创建store时使用到
